/*
 * utils.c
 *
 *  Created on: Jul 1, 2024
 *      Author: PIANO
 */
#include "utils.h"

/**
 * tickDelta
 *
 */
int32_t tickDelta(__IO uint32_t *lastTick) {
	uint32_t thisTick = HAL_GetTick();
	int32_t delta = (int32_t) (thisTick - *lastTick);
	*lastTick = thisTick;
	return delta;
}

/**
 * DIO滤波
 *
 * @param
 * @return
 */
void digitalFilter(bool *output, bool input, uint32_t filterTimeSet,
		uint32_t *timeCount) {
	// 输入为true，时间增长，增长到设定值不再增长，输出设定为true
	if (input) {
		//判断滤波器数值
		if (*timeCount < filterTimeSet)
			(*timeCount)++;
		else
			*output = true;
	}
	// 输入为false，计次减少，减少到0不再减少，输出设定为false
	else {
		//判断滤波器数值
		if (*timeCount > 0)
			(*timeCount)--;
		else
			*output = false;
	}
}

/**
 * 信号边缘判断 posedge
 *
 * @param
 * @return
 */
bool isPosedge(bool in, bool *lastIn) {
	bool result = in && !*lastIn;
	*lastIn = in;
	return result;
}

/**
 * 信号边缘判断 negedge
 *
 * @param
 * @return
 */
bool isNegedge(bool in, bool *lastIn) {
	bool result = !in && *lastIn;
	*lastIn = in;
	return result;
}

/**
 * 字节组成16位
 *
 */
int16_t toInt16(uint8_t *bytes) {

	return (int16_t) (bytes[0] | bytes[1] << 8);
}

/**
 * 字节组成16位
 *
 */
uint16_t toUint16(uint8_t *bytes) {

	return (uint16_t) (bytes[0] | bytes[1] << 8);
}

/**
 * 字节组成32位
 *
 */
int32_t toInt32(uint8_t *bytes) {

	return (int32_t) (bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24);
}

/**
 * 字节组成32位
 *
 */
uint32_t toUint32(uint8_t *bytes) {

	return (uint32_t) (bytes[0] | bytes[1] << 8 | bytes[2] << 16
			| bytes[3] << 24);
}

/**
 * u16ToFloat
 *
 */
float u16ToFloat(uint16_t *pSrc) {
	union {
		uint16_t s[2];
		float f;
	} u;
	u.s[1] = *pSrc;
	u.s[0] = *(pSrc + 1);
	return u.f;
}

/**
 * word转2byte
 *
 */
void toBytes2(uint8_t *bytes, uint16_t word) {

	bytes[0] = word & 0xFF;
	bytes[1] = (word >> 8) & 0xFF;
}

/**
 * dword转4byte
 *
 */
void toBytes4(uint8_t *bytes, uint32_t dword) {

	bytes[0] = dword & 0xFF;
	bytes[1] = (dword >> 8) & 0xFF;
	bytes[2] = (dword >> 16) & 0xFF;
	bytes[3] = (dword >> 24) & 0xFF;
}

/**
 * int8 limit
 *
 * @param
 * @return
 */
void int8Limit(int8_t *value, int8_t min, int8_t max) {
	if (*value < min)
		*value = min;
	if (*value > max)
		*value = max;
}

/**
 * uint8 limit
 *
 * @param
 * @return
 */
void uint8Limit(uint8_t *value, uint8_t min, uint8_t max) {
	if (*value < min)
		*value = min;
	if (*value > max)
		*value = max;
}

/**
 * int16 limit
 *
 * @param
 * @return
 */
void int16Limit(int16_t *value, int16_t min, int16_t max) {
	if (*value < min)
		*value = min;
	if (*value > max)
		*value = max;
}

/**
 * uint16 limit
 *
 * @param
 * @return
 */
void uint16Limit(uint16_t *value, uint16_t min, uint16_t max) {
	if (*value < min)
		*value = min;
	if (*value > max)
		*value = max;
}
